package com.northpool.operator.common.database;

import com.northpool.operator.common.database.bean.NacosProperties;
import org.apache.commons.lang3.StringUtils;

/**
 * 从环境变量中读取
 * Linux
   export NACOS_SERVER_ADDR="land.data-hub.info:8848"
   export NACOS_GROUP="dev"
   export NACOS_NAMESPACE="dev"
   export NACOS_USERNAME="nacos"
   export NACOS_PASSWORD="admin"
 * Windows
   set NACOS_SERVER_ADDR=land.data-hub.info:8848
   set NACOS_GROUP=dev
   set NACOS_NAMESPACE=dev
   set NACOS_USERNAME=nacos
   set NACOS_PASSWORD=admin
 *  NACOS_SERVER_ADDR=land.data-hub.info:8848;NACOS_GROUP=dev;NACOS_NAMESPACE=dev;NACOS_USERNAME=nacos;NACOS_PASSWORD=admin
 */
public class NacosConfigReader {

    public static NacosProperties getNacosProperties() {
        String serverAddr = getRequiredEnvVar("NACOS_SERVER_ADDR");
        String group = getRequiredEnvVar("NACOS_GROUP");
        String namespace = getRequiredEnvVar("NACOS_NAMESPACE");
        String username = getRequiredEnvVar("NACOS_USERNAME");
        String password = getRequiredEnvVar("NACOS_PASSWORD");
        if (StringUtils.isBlank(serverAddr)) {
            serverAddr = "192.168.5.50:8848";
            group = "dev";
            namespace = "dev";
            username = "nacos";
            password = "admin";
        }

        System.out.println("NACOS_SERVER_ADDR: " + serverAddr);

        NacosProperties properties = new NacosProperties();

        properties.setServerAddr(serverAddr);
        properties.setNamespace(namespace);
        properties.setUsername(username);
        properties.setPassword(password);
        properties.setGroup(group);

        return properties;
    }

    private static String getRequiredEnvVar(String envVarName) {
        String value = System.getenv(envVarName);
        if (value == null || value.isEmpty()) {
//            throw new IllegalArgumentException("Environment variable " + envVarName + " is not set or empty");
        }
        return value;
    }
}
